/**********************************************************************************
Copyright (C), by AppleCai
Project                      : Study Kernel driver
Description                  : User Application for cdev
History                      :
CPU and Compiler             : AM335x,GCC
GenDate                      : 2020-10-24
OwnerBy                      : Apple Cai
**********************************************************************************/
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"

#define SUPPORT_NONBLOCK  0  /* test */
static char usrdata[] = {"usr data!"};

/*
 * @description		: main主程序
 * @param - argc 	: argv数组元素个数
 * @param - argv 	: 具体参数
 * @return 			: 0:成功;others:失败
 */
int main(int argc, char *argv[])
{
	int fd, retvalue;
	char *filename;
	char readbuf;

	if(argc != 2){
		printf("Error Usage!Please set filename and control flag\r\n");
		return -1;
	}

	filename = argv[1];

	/* 打开驱动文件 */
	#if SUPPORT_NONBLOCK
	fd  = open(filename, O_RDWR|O_NONBLOCK);
	#else
	fd  = open(filename, O_RDWR);
	#endif
	if(fd < 0){
		printf("Can't open file %s\r\n", filename);
		return -1;
	}

	while(1)
	{
		#if SUPPORT_NONBLOCK

		while(read(fd, &readbuf, 1)!=1)
			continue;
		printf("%c",readbuf);

		#else
		/* read each one */
		retvalue = read(fd, &readbuf, 1);
		if(retvalue ==1)
		{
			printf("%c",readbuf);
		}
		else if(retvalue < 0){
			printf("read file %s failed!\r\n", filename);
		}
		else
		{}
		#endif

	}

	/* close */
	retvalue = close(fd);
	if(retvalue < 0){
		printf("Can't close file %s\r\n", filename);
		return -1;
	}
	return 0;
}
